<?php
/**
 * @file ct.comic.todirectorybypath.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-01-26 03:31:30 +0000 (Sat, 26 Jan 2013) $
 *
 * $Id: ct.comic.todirectorybypath.php 56 2013-01-26 03:31:30Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0-BETA1/cron/ct.comic.todirectorybypath.php $
 */
class WCComicsToDirectoryPath extends WCCronTool {
	protected	$_db		= null;
	protected	$_dbprefix	= "";

	public function run($spacer="") {
		global	$wcOptions;
		global	$wcDatabaseAccess;

		$this->_db		= WCConnection::Instance();
		$this->_dbprefix	= $wcDatabaseAccess['prefix'];

		$log = WCLog::Get(WC_LOGNAME_CRON);
		if(!$log->isOk()) {
			$log->set();
		}

		$moved = false;

		if($wcOptions->activated("From") && $wcOptions->activated("To")) {
			$ok = true;

			$fromPath	= $this->clearPath("/{$wcOptions->value("From")}");
			$toPath		= $this->clearPath("/{$wcOptions->value("To")}");

			$from	= $this->getPathInfo($fromPath);
			$to	= $this->getPathInfo($toPath);

			// Checks.
			// @{
			if($ok) {
				if(!$from["group"] || !$from["directory"] || !$to["group"] || !$to["directory"]) {
					$ok = false;
					$log->write("Error: Unable to retrive basic information from both paths.\n", WCLogLevel::Fatal);
				}
			}
			if($ok) {
				if(!$from["comic"]) {
					$ok = false;
					$log->write("Error: Origin path '{$fromPath}' is not a valid comic path.\n", WCLogLevel::Fatal);
				}
			}
			if($ok) {
				if($from["group"]->id != $to["group"]->id) {
					$ok = false;
					$log->write("Error: Cross-group moves are not allowed.\n", WCLogLevel::Fatal);
				}
			}
			// @}

			if($ok) {
				// Summary.
				$log->write("{$spacer}Group:     '{$from["group"]->name}' ({$from["group"]->id})\n");
				$log->write("{$spacer}\troot: '{$from["group"]->root}'\n");
				$log->write("{$spacer}Comic:     '{$from["comic"]->name}' ({$from["comic"]->id})\n");
				$log->write("{$spacer}\tat:   '{$from["comic"]->directory()->name}' ({$from["comic"]->directory})\n");
				$log->write("{$spacer}Directory: '{$to["directory"]->name}' ({$to["directory"]->id})\n");

				if(!$from["comic"]->setDirectory($to["directory"])) {
					$ok = false;
					$log->write("Error: Unable to move '{$from["comic"]->id}' to directory '{$to["directory"]->id}'.\n", WCLogLevel::Fatal);
				}
			}
		} else {
			$this->showHelp($spacer);
		}

		return $moved;
	}
	public function showHelp($spacer="") {
		echo "{$spacer}This tool moves a comic to a directory.\n\n";
		echo "{$spacer}Options:\n";
		echo "{$spacer}\t-f comic-path, --from comic-path\n";
		echo "{$spacer}\t\tComic path.\n\n";
		echo "{$spacer}\t-t dir-path, --to dir-path\n";
		echo "{$spacer}\t\tDirectory path.\n";
	}

	protected function clearPath($path) {
		$out = $path;

		while(strpos($out, "//") !== false) {
			$out = str_replace("//", "/", $out);
		}
		if(substr($out,strlen($out)-1) == "/") {
			$out = substr($out, 0, strlen($out)-1);
		}

		return $out;
	}
	protected function getPathInfo($path) {
		global	$wcGroupsHolder;
		global	$wcPatterns;

		$info = array(
				"group"		=> false,
				"directory"	=> false,
				"comic"		=> null
		);

		$dirPath	= $path;
		$comicName	= false;
		foreach($wcPatterns['comic-patterns'] as $pattern) {
			if(preg_match($pattern, $path)) {
				$dirPath	= dirname($path);
				$comicName	= basename($path);
				break;
			}
		}

		$stmt	= null;
		$stmtID	= __CLASS__."::".__FUNCTION__."[group]";
		if($this->_db->has($stmtID)) {
			$stmt = $this->_db->get($stmtID);
		} else {
			$query = "select  *\n";
			$query.= "from    {$this->_dbprefix}groups\n";
			$query.= "where   :path like concat(grp_root,'%')\n";

			$stmt  = $this->_db->prepare($stmtID, $query);
		}
		if($stmt->execute(array(":path" => $dirPath))) {
			global	$wcDirectoriesHolder;

			foreach($stmt->fetchAll() as $groupRow) {
				$info["group"] =  $wcGroupsHolder->groupById($groupRow["grp_id"]);

				$subPath = substr($dirPath, strlen($info["group"]->root));

				$info["directory"] = $wcDirectoriesHolder->itemByName($subPath, $info["group"]);
				if($info["directory"] && $info["directory"]->ok()) {
					if($comicName) {
						$stmtC	= null;
						$stmtID	= __CLASS__."::".__FUNCTION__."[comic]";
						if($this->_db->has($stmtID)) {
							$stmtC	= $this->_db->get($stmtID);
						} else {
							$query = "select  *\n";
							$query.= "from    {$this->_dbprefix}comics\n";
							$query.= "where   cmc_group     = :group\n";
							$query.= " and    cmc_directory = :directory\n";
							$query.= " and    cmc_name      = :name\n";

							$stmtC	= $this->_db->prepare($stmtID, $query);
						}

						$params = array(
								":group"	=> $info["group"]->id,
								":directory"	=> $info["directory"]->id,
								":name"		=> $comicName
						);
						if($stmtC->execute($params) && $stmtC->rowCount() > 0) {
							global	$wcComicsHolder;

							$row		= $stmtC->fetch();
							$info["comic"]	= $wcComicsHolder->item($row["cmc_id"], $info["group"]);

							if(!$info["comic"] || !$info["comic"]->ok()) {
								$info["comic"] = false;
							}
						}
					}
				} else {
					$info["group"]		= null;
					$info["directory"]	= null;
				}
			}
		}

		return $info;
	}
	protected function loadOptions() {
		if(!$this->_optionsLoaded) {
			global	$wcOptions;

			if($wcOptions->addValueOption("From")) {
				$wcOptions->addOptionTrigger("From", "f");
				$wcOptions->addOptionTrigger("From", "from");
			}
			if($wcOptions->addValueOption("To")) {
				$wcOptions->addOptionTrigger("To", "t");
				$wcOptions->addOptionTrigger("To", "to");
			}

			$wcOptions->check();

			$this->_optionsLoaded = true;
		}
	}
}
?>
